<template>
  <div>
    <div class="gva-search-box">
      <el-form :inline="true" :model="searchInfo" class="demo-form-inline" @keyup.enter="onSubmit">
        <el-form-item label="创建时间">
          <el-date-picker v-model="searchInfo.startCreatedAt" type="datetime" placeholder="开始时间" />
          —
          <el-date-picker v-model="searchInfo.endCreatedAt" type="datetime" placeholder="结束时间" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="onSubmit">查询</el-button>
          <el-button icon="refresh" @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="gva-table-box">
      <div class="gva-btn-list">
        <el-button type="primary" icon="plus" @click="openDialog">新增</el-button>
        <el-popover v-model:visible="deleteVisible" placement="top" width="160">
          <p>确定要删除吗？</p>
          <div style="text-align: right; margin-top: 8px;">
            <el-button type="primary" link @click="deleteVisible = false">取消</el-button>
            <el-button type="primary" @click="deleteSelectedRow">确定</el-button>
          </div>
          <template #reference>
            <el-button icon="delete" style="margin-left: 10px;" :disabled="!multipleSelection.length" @click="deleteVisible = true">删除</el-button>
          </template>
        </el-popover>
      </div>

      <el-table
        ref="multipleTable"
        style="width: 100%"
        border
        :header-cell-style="{background:'#a3c6d2',color:'#849ba1'}"
        tooltip-effect="dark"
        :data="tableData"
        row-key="ID"
        @selection-change="handleSelectionChange"
      >
        <el-table-column align="left" label="接口ID" prop="ID" :show-overflow-tooltip="true" />
        <el-table-column align="left" label="主题名称" prop="topicId" :show-overflow-tooltip="true">
          <template #default="scope">{{ getTopicNameById(scope.row.topicId) }}</template>
        </el-table-column>
        <el-table-column align="left" label="主题编码" prop="topicId" :show-overflow-tooltip="true">
          <template #default="scope">{{ getTopicCodeById(scope.row.topicId) }}</template>
        </el-table-column>
        <el-table-column align="left" label="接口名称" prop="name" :show-overflow-tooltip="true" />
        <el-table-column align="left" label="接口编码" prop="code" :show-overflow-tooltip="true" />
        <el-table-column align="left" label="接口类型" prop="type" :show-overflow-tooltip="true" />
        <el-table-column align="left" label="请求方式" prop="request" :show-overflow-tooltip="true" />
        <el-table-column align="left" label="状态" prop="status" :show-overflow-tooltip="true">
          <template #default="scope">{{ stateBoolean(scope.row.status) }}</template>
        </el-table-column>
        <el-table-column align="left" label="备注" prop="remark" :show-overflow-tooltip="true" />
        <el-table-column align="left" label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button type="primary" link icon="edit" class="table-button" @click="editRow(scope.row)">变更</el-button>
            <el-button type="primary" link icon="delete" @click="deleteRow(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination
          layout="total, sizes, prev, pager, next, jumper"
          :current-page="page"
          :page-size="pageSize"
          :page-sizes="[10, 30, 50, 100]"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>
    <el-dialog
      v-model="dialogFormVisible"
      :before-close="closeDialog"
      :title="dialogTitle"
      width="80%"
    >
      <el-form
        ref="elFormRef"
        class="x-form"
        :model="dwsApi"
        label-position="right"
        :rules="rule"
        :inline="true"
      >
        <el-form-item label="数据主题:" prop="topicId" style="width:22%">
          <el-select v-model="dwsApi.topicId" style="width:100%" placeholder="选择数据主题" @change="getTopicCode">
            <el-option v-for="item in dwsTopics" :key="item.id" :value="item.ID" :label="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="主题编码:" prop="topicCode" style="width:22%">
          <el-input v-model="dwsApi.topicCode" :disabled="true" />
        </el-form-item>
        <el-form-item label="接口名称:" prop="name" style="width:22%">
          <el-input v-model="dwsApi.name" placeholder="请输入" @change="checkName" />
        </el-form-item>
        <el-form-item label="接口编码:" prop="code" style="width:22%">
          <el-input v-model="dwsApi.code" placeholder="请输入" @change="checkCode" />
        </el-form-item>
        <el-form-item label="接口类型:" prop="type" style="width:22%">
          <el-select v-model="dwsApi.type" style="width:100%">
            <el-option v-for="item in apiType" :key="item.id" :value="item.label" :label="item.label" />
          </el-select>
        </el-form-item>
        <el-form-item label="请求方式:" prop="request" style="width:22%">
          <el-select v-model="dwsApi.request" style="width:100%">
            <el-option v-for="item in requestType" :key="item.id" :value="item.label" :label="item.label" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态:" prop="status" style="width:22%">
          <el-switch v-model="dwsApi.status" active-color="#13ce66" inactive-color="#ff4949" active-text="启用" inactive-text="停用" clearable />
        </el-form-item>
        <el-form-item label="更多配置:" prop="remark" style="width:22%">
          <el-button type="primary" @click="updateRemark">更多配置 ...</el-button>
        </el-form-item>
      </el-form>
      <el-form
        ref="elFormRefDwsTb"
        class="x-form"
        :model="dwsTb"
        label-position="right"
        :rules="ruleDwsTb"
        :inline="true"
      >
        <el-form-item label="选择数据表:">
          <template v-for="(item,index) in dwsTbs" :key="item">
            <template v-if="dwsTbs.length>0 && index<(dwsTbs.length) && index>0">
              <el-select v-model="item.joinType" style="width:100px; margin:3px;" placeholder="连接方式">
                <el-option v-for="joinType in joinTypeList" :key="joinType.id" :value="joinType.label" :label="joinType.label" />
              </el-select>
            </template>
            <el-button v-if="item.srcTbExist===1" :icon="Delete" type="success" @click="delSrcTb(item.srcTbId)">{{ item.srcTbName }}</el-button>
            <el-button v-if="item.srcTbExist ===0" :icon="Delete" type="danger" @click="delSrcTb(item.srcTbId)">{{ item.srcTbName }}</el-button>
            <template v-if="dwsTbs.length>0 && index<(dwsTbs.length) && index>0">
              <span style="margin:5px;">on</span>
              <el-select v-model="dwsTbs[index-1].joinOn" style="width:100px" placeholder="选择列名">
                <el-option v-for="joinOn in dwsTbs[index-1].colList" :key="joinOn" :value="joinOn" :label="joinOn" />
              </el-select>
              <span style="margin:5px;">=</span>
              <el-select v-model="item.joinOn" style="width:100px" placeholder="选择列名">
                <el-option v-for="joinOn in item.colList" :key="joinOn" :value="joinOn" :label="joinOn" />
              </el-select>
            </template>

          </template>
          <el-button style="margin:5px;" type="primary" icon="plus" @click="openTbDialog">新增表</el-button>
        </el-form-item>

      </el-form>
      <el-row v-if="dwsTbs" :gutter="20">
        <el-col :span="7">
          <el-card>
            <template #header>
              <div class="card-header" style="text-align:center">
                <span>数据选择</span>
              </div>
            </template>

            <div v-for="item in dwsTbs" :key="item">
              <div style="text-align:center">
                <span>表名: {{ item.srcTbName }} ({{ item.srcTbId }})</span><el-icon style="float: right"><DArrowRight /></el-icon>
              </div>
              <el-table
                ref="multipleTable"
                :key="refreshTb.value"
                style="width: 100%"
                :size="'small'"
                border
                tooltip-effect="dark"
                :data="item.srcFlds"
                :row-style="{height:'20px'}"
                :cell-style="{padding:'0px'}"
                :header-cell-style="{background:'#a3c6d2',color:'#849ba1',padding:'0px'}"
              >
                <el-table-column align="left" label="列类型" prop="odsColType" :show-overflow-tooltip="true" />
                <el-table-column align="left" label="列注释" prop="odsColComment" :show-overflow-tooltip="true" />
                <el-table-column align="left" label="列名称" prop="odsColName" :show-overflow-tooltip="true" />
                <el-table-column align="left" label="选择" prop="selected" width="60" fixed="right">
                  <template #default="scope">
                    <el-button v-if="!scope.row.selected" size="small" icon="ArrowRightBold" @click="selectFld(scope.row)" />
                    <el-button v-if="scope.row.selected" size="small" icon="Select" type="success" @click="selectFld(scope.row)" />
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-card>
        </el-col>
        <el-col :span="9">
          <el-card>
            <template #header>
              <div class="card-header" style="text-align:center">
                <span>接口数据 (如红色:数据异常)</span>
              </div>
            </template>

            <div style="text-align:center">
              <el-icon style="float: left"><DArrowLeft /></el-icon> <span>接口名称: {{ dwsApi.code }}</span>
            </div>

            <el-table
              ref="multipleTable"
              style="width: 100%"
              border
              :size="'small'"
              :cell-style="{padding:'0px'}"
              :header-cell-style="{background:'#a3c6d2',color:'#f1f4f5',padding:'0px'}"
              tooltip-effect="dark"
              :data="dwsFlds"
              row-key="ID"
              :row-style="changeBackRed"
            >
              <el-table-column align="left" label="删除" width="60" fixed="left">
                <template #default="scope">
                  <el-icon @click="deleteDwsFld(scope.row.srcFldId)"><ArrowLeftBold /></el-icon>
                </template>
              </el-table-column>
              <el-table-column align="left" label="源表ID" prop="srcTbId" width="80" />
              <el-table-column align="left" label="源表列名" prop="srcFldName" :show-overflow-tooltip="true" />
              <el-table-column align="left" label="列类型" prop="srcFldType" :show-overflow-tooltip="true" />
              <el-table-column align="left" label="接口列名" prop="dwsFldName" width="180">
                <template #default="{row}">
                  <el-input v-model="row.dwsFldName" />
                </template>
              </el-table-column>

            </el-table>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card>
            <template #header>
              <div class="card-header" style="text-align:center">
                <span>SQL预览</span>
              </div>
            </template>

            <template v-if="dwsFlds">
              <span>select{{ space }}<br></span>
              <template v-for="(item,idx) in dwsFlds" :key="item">
                <span v-if="idx<dwsFlds.length-1">t{{ item.srcTbId }}.{{ item.srcFldName }} {{ item.dwsFldName }},<br></span>
                <span v-else>t{{ item.srcTbId }}.{{ item.srcFldName }} {{ item.dwsFldName }}{{ space }}<br></span>
              </template>

              <span>from{{ space }}<br></span>
              <template v-for="(item, index) in dwsTbs" :key="item">
                <template v-if="item.joinType">
                  {{ item.joinType }}<br>
                </template>
                {{ item.srcTbName }} t{{ item.srcTbId }}<br>
                <template v-if="item.joinOn && index>0">
                  <span>on{{ space }}<br></span>
                  t{{ dwsTbs[index-1].srcTbId }}.{{ dwsTbs[index-1].joinOn }}=t{{ item.srcTbId }}.{{ item.joinOn }}<br>
                </template>
              </template>
              where ...<br>
            </template>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card>
            <template #header>
              <div class="card-header" style="text-align:center">
                <span>接口示例</span>
              </div>
            </template>

            数据请求方式:{{ dwsApi.request }}<br><br>
            数据请求url:{{ dwsApi.request }}<br><br>
            数据请求示例:<br>
            {<br>
            topic:{{ dwsApi.topicCode }}<br>
            name:{{ dwsApi.code }}<br>
            param:[{<br>
            colName:xxx<br>
            condition:= '大/小/等/不等'<br>
            colValue:xxx<br>
            }]<br>
            }<br><br>
            数据响应示例:<br>
            {<br>
            code:{{ 200 }}<br>
            data:{ [{},{...}] }<br>
            msg:"..."<br>
            }<br>
          </el-card>
        </el-col>
      </el-row>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="testApi">测 试</el-button>
          <el-button @click="closeDialog">取 消</el-button>
          <el-button type="primary" @click="saveApi">保 存</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      v-model="dialogRemarkVisible"
      :before-close="closeRemark"
      title="备注"
      width="40%"
    >
      <el-form
        ref="elFormRef"
        :model="dwsApi"
        label-position="right"
        :rules="rule"
        label-width="60px"
        :inline="true"
      >
        <el-form-item label="黑名单:" prop="deny" style="width:100%">
          <el-input v-model="dwsApi.deny" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="备注:" prop="remark" style="width:100%">
          <el-input
            v-model="dwsApi.remark"
            :clearable="true"
            placeholder="请输入"
            type="textarea"
            :rows="4"
          />
        </el-form-item>
        <el-row>
          <el-col>
            <el-button style="float: right" type="primary" @click="saveRemark">确 定</el-button>
            <el-button style="float: right; margin-right:10px;" @click="closeRemark">取 消</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>
    <el-dialog v-model="dialogDwsTbVisible" :before-close="closeDwsTbDialog" title="选择源数据">
      <el-form
        ref="elFormSrcTb"
        :model="dwsTb"
        label-position="right"
        :rules="ruleDwsTb"
        label-width="100px"
        :inline="true"
      >
        <el-form-item label="源schema:" prop="srcSchema" style="width:40%">
          <el-select v-model="dwsTb.srcSchema" clearable style="width:100%" placeholder="请选择源schema">
            <el-option v-for="item in schemaList" :key="item" :value="item" :label="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="源表名称:" prop="srcTbId" style="width:40%">
          <el-select v-model="dwsTb.srcTbId" clearable style="width:100%" filterable placeholder="请选择源数据表">
            <el-option v-for="item in allOdsTbs" :key="item.id" :value="item.ID" :label="item.odsTbName" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDwsTbDialog">取 消</el-button>
          <el-button type="primary" @click="addDwsTb">确 定</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script>
export default {
  name: 'DwsApi'
}
</script>

<script setup>
import {
  createDwsApi,
  deleteDwsApi,
  deleteDwsApiByIds,
  updateDwsApi,
  getDwsApiList,
  getDwsApi,
  getAllDwsApis
} from '@/api/dwsApi'

import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, reactive, onMounted } from 'vue'
import { getAllDwsTopics } from '@/api/dwsTopic'
import { getDict } from '@/utils/dictionary'
import { getAllOdsDbTables } from '@/api/odsDbTable'
import { getOdsFldsByTbId } from '@/api/odsDbField'
import { ArrowLeftBold, ArrowRightBold, DArrowLeft, DArrowRight, Delete } from '@element-plus/icons-vue'
const space = ref(' ')

const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const tableData = ref([])
const searchInfo = ref({})

const onReset = () => {
  searchInfo.value = {}
  getTableData()
}

const onSubmit = () => {
  page.value = 1
  pageSize.value = 10
  if (searchInfo.value.status === '') {
    searchInfo.value.status = null
  }
  getTableData()
}

const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}

const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}

const getTableData = async() => {
  const table = await getDwsApiList({ page: page.value, pageSize: pageSize.value, ...searchInfo.value })
  if (table.code === 0) {
    tableData.value = table.data.list
    total.value = table.data.total
    page.value = table.data.page
    pageSize.value = table.data.pageSize
  }
}
const setOptions = async() => {
}

setOptions()

const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

const deleteRow = (row) => {
  ElMessageBox.confirm('确定要删除吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    clickDeleteDwsApi(row)
  })
}

const deleteVisible = ref(false)

const deleteSelectedRow = async() => {
  const ids = []
  if (multipleSelection.value.length === 0) {
    ElMessage({
      type: 'warning',
      message: '请选择要删除的数据'
    })
    return
  }
  multipleSelection.value &&
  multipleSelection.value.map(item => {
    ids.push(item.ID)
  })
  const res = await deleteDwsApiByIds({ ids })
  if (res.code === 0) {
    ElMessage({
      type: 'success',
      message: '删除成功'
    })
    if (tableData.value.length === ids.length && page.value > 1) {
      page.value--
    }
    deleteVisible.value = false
    await getTableData()
  }
}
const clickDeleteDwsApi = async(row) => {
  const res = await deleteDwsApi({ ID: row.ID })
  if (res.code === 0) {
    ElMessage({
      type: 'success',
      message: '删除成功'
    })
    if (tableData.value.length === 1 && page.value > 1) {
      page.value--
    }
    await getTableData()
  }
}
const dwsApi = ref({
  topicId: 0,
  topicName: '',
  topicCode: '',

  name: '',
  code: '',
  type: '',
  request: '',
  deny: '',
  status: false,
  remark: '',
})
const dswApiReset = async() => {
  dwsApi.value = {
    topicId: 0,
    topicName: '',
    topicCode: '',

    name: '',
    code: '',
    type: '',
    request: '',
    deny: '',
    status: false,
    remark: '',
  }
}
const dwsTbsReset = async() => {
  dwsTbs.value = []
}
const dwsFldsReset = async() => {
  dwsFlds.value = []
}

const rule = reactive({
  topicId: [{
    required: true,
    message: '',
    trigger: ['input', 'blur'],
  }],
  name: [{
    required: true,
    message: '',
    trigger: ['input', 'blur'],
  }],
  code: [{
    required: true,
    message: '',
    trigger: ['input', 'blur'],
  }],
  type: [{
    required: true,
    message: '',
    trigger: ['input', 'blur'],
  }],
  request: [{
    required: true,
    message: '',
    trigger: ['input', 'blur'],
  }],
})
const elFormRef = ref()
const saveType = ref('')
const dialogFormVisible = ref(false)
const dialogTitle = ref()
const refreshTb = ref(false)
const refreshSelect = () => {
  if (dwsTbs.value.length > 0) {
    for (let i = 0; i < dwsTbs.value.length; i++) {
      if (dwsTbs.value[i].srcFlds !== null) {
        for (let j = 0; j < dwsTbs.value[i].srcFlds.length; j++) {
          dwsTbs.value[i].srcFlds[j].selected = false
          let m = 0
          for (let k = 0; k < dwsFlds.value.length; k++) {
            if (dwsTbs.value[i].srcFlds[j].ID === dwsFlds.value[k].srcFldId) {
              dwsTbs.value[i].srcFlds[j].selected = true
            } else {
              m++
            }
          }
          if (m === dwsFlds.value.length) {
            dwsTbs.value[i].srcFlds[j].selected = false
          }
        }
      }
    }
  }
  refreshTb.value = !refreshTb.value
}
const editRow = async(row) => {
  saveType.value = 'update'
  const res = await getDwsApi(row.ID)
  if (res.code === 0) {
    await dswApiReset()
    await dwsTbsReset()
    await dwsFldsReset()
    dwsApi.value = res.data.apiConfig.dwsApi
    dwsTbs.value = res.data.apiConfig.dwsTbs
    dwsFlds.value = res.data.apiConfig.dwsFlds
    refreshSelect()

    dialogTitle.value = '编辑接口配置'
    dialogFormVisible.value = true
  }
}
const openDialog = () => {
  saveType.value = 'create'
  dialogTitle.value = '新增接口配置'
  dialogFormVisible.value = true
}
const closeDialog = () => {
  dialogFormVisible.value = false
  dswApiReset()
  dwsTbsReset()
  dwsFldsReset()
}
const saveApi = async() => {
  elFormRef.value?.validate(async(valid) => {
    if (!valid) return
    let res
    switch (saveType.value) {
      case 'create':
        res = await createDwsApi({ dwsApi: dwsApi.value, dwsTbs: dwsTbs.value, dwsFlds: dwsFlds.value })
        break
      case 'update':
        res = await updateDwsApi({ dwsApi: dwsApi.value, dwsTbs: dwsTbs.value, dwsFlds: dwsFlds.value })
        break
      default:
        ElMessage({
          type: 'success',
          message: '未定义保存方式'
        })
        break
    }
    if (res.code === 0) {
      ElMessage({
        type: 'success',
        message: res.msg
      })
      closeDialog()
      await getTableData()
    }
  })
}
const dialogRemarkVisible = ref(false)

const updateRemark = () => {
  dialogRemarkVisible.value = true
}

const closeRemark = () => {
  dialogRemarkVisible.value = false
}
const saveRemark = async() => {
  closeRemark()
}

const getTopicCode = (data) => {
  for (let i = 0; i < dwsTopics.value.length; i++) {
    if (data === dwsTopics.value[i].ID) {
      dwsApi.value.topicName = dwsTopics.value[i].Name
      dwsApi.value.topicCode = dwsTopics.value[i].code
    }
  }
}
const checkName = (data) => {
  for (let i = 0; i < apiNameList.value.length; i++) {
    if (data === apiNameList.value[i]) {
      dwsApi.value.name = ''
      ElMessage({
        type: 'warning',
        message: 'api名称重复'
      })
    }
  }
}
const checkCode = (data) => {
  for (let i = 0; i < apiCodeList.value.length; i++) {
    if (data === apiCodeList.value[i]) {
      dwsApi.value.code = ''
      ElMessage({
        type: 'warning',
        message: 'api编码重复'
      })
    }
  }
}

const schemaList = ref(
  ['xidw-ods']
)
const dwsTbs = ref([])
const dwsTb = ref({
  srcSchema: '',
  srcTbId: '',
  srcTbName: '',

  joinType: '',
  joinOn: '',
  joinOnType: '',

  srcFlds: [],
  colList: [],
})
const dwsTbReset = async() => {
  dwsTb.value = {
    srcSchema: '',
    srcTbId: '',
    srcTbName: '',
    SrcTbExist: 0,

    joinType: '',
    joinOn: '',
    joinOnType: '',

    srcFlds: [],
    colList: [],
  }
}
const ruleDwsTb = reactive({
  srcSchema: [{
    required: true,
    message: '',
    trigger: ['input', 'blur'],
  }],
  srcTbId: [{
    required: true,
    message: '',
    trigger: ['input', 'blur'],
  }],
})
const dialogDwsTbVisible = ref()
const dialogDwsTbTitle = ref()
const dlgTbType = ref('')
const openTbDialog = () => {
  dlgTbType.value = 'create'
  dialogDwsTbTitle.value = '选择数据源'
  dialogDwsTbVisible.value = true
}

const closeDwsTbDialog = () => {
  dialogDwsTbVisible.value = false
  dwsTbReset()
}
const addDwsTb = async() => {
  if (dwsTb.value.srcSchema && dwsTb.value.srcTbId) {
    for (let i = 0; i < dwsTbs.value.length; i++) {
      if (dwsTb.value.srcSchema === dwsTbs.value[i].srcSchema &&
          dwsTb.value.srcTbId === dwsTbs.value[i].srcTbId) {
        ElMessage({
          type: 'success',
          message: '此表已经选择'
        })
        await dwsTbReset()
        return
      }
    }
    const res = await getOdsFldsByTbId(dwsTb.value.srcTbId)
    if (res.code === 0) {
      dwsTb.value.srcFlds = res.data.odsFlds
      for (const oneFld of dwsTb.value.srcFlds) {
        dwsTb.value.colList.push(oneFld.odsColName)
      }
    } else {
      ElMessage({
        type: 'info',
        message: '根据表ID获取ODS字段信息失败'
      })
    }
    for (let i = 0; i < allOdsTbs.value.length; i++) {
      if (allOdsTbs.value[i].ID === dwsTb.value.srcTbId) {
        dwsTb.value.srcTbName = allOdsTbs.value[i].odsTbName
        dwsTb.value.srcTbBsm = allOdsTbs.value[i].bsm
      }
    }
    if (!dwsTb.value.srcTbName) {
      dwsTb.value.srcTbExist = 0
      ElMessage({
        type: 'info',
        message: '未能查询到此表'
      })
      return
    } else {
      dwsTb.value.srcTbExist = 1
    }
    dwsTb.value.ID = 0
    dwsTbs.value.push(dwsTb.value)
  } else {
    ElMessage({
      type: 'info',
      message: '请填写完整信息'
    })
    return
  }
  await closeDwsTbDialog()
}
const dwsFld = ref({
  srcTbId: '',
  srcTbName: '',

  srcFldId: '',
  srcFldName: '',
  srcFldType: '',

  dwsFldName: '',
})
const dwsFldReset = async() => {
  dwsFld.value = {
    srcTbId: '',
    srcTbName: '',

    srcFldId: '',
    srcFldName: '',
    srcFldType: '',

    dwsFldName: '',
  }
}

const dwsFlds = ref([])
const selectFld = async(data) => {
  for (const one of dwsFlds.value) {
    if (one.srcFldId === data.ID) {
      dwsFlds.value = dwsFlds.value.filter(t => t.srcFldId !== data.ID)
      refreshSelect()
      return
    }
  }
  dwsFld.value.srcTbId = data.odsTbId
  dwsFld.value.srcTbName = data.odsTbName

  dwsFld.value.srcFldId = data.ID
  dwsFld.value.srcFldName = data.odsColName
  dwsFld.value.srcFldType = data.odsColType
  dwsFld.value.dwsFldName = data.odsColName

  dwsFlds.value.push(dwsFld.value)
  await dwsFldReset()
  refreshSelect()
  return true
}

const deleteDwsFld = async(data) => {
  for (let i = 0; i < dwsFlds.value.length; i++) {
    if (dwsFlds.value[i].srcFldId === data) {
      dwsFlds.value = dwsFlds.value.filter(t => t.srcFldId !== data)
    }
  }
  refreshSelect()
}

const deleteDwsFlds = async(data) => {
  for (let i = 0; i < dwsFlds.value.length; i++) {
    if (dwsFlds.value[i].srcTbId === data) {
      dwsFlds.value = dwsFlds.value.filter(t => t.srcTbId !== data)
    }
  }
}
const delSrcTb = async(data) => {
  for (let i = 0; i < dwsTbs.value.length; i++) {
    if (dwsTbs.value[i].srcTbId === data) {
      dwsTbs.value = dwsTbs.value.filter(t => t.srcTbId !== data)
      await deleteDwsFlds(data)
    }
  }
  if (dwsTbs.value.length === 0) {
    dwsFlds.value = []
  }
}
const changeBackRed = ({ row }) => {
  if (row.srcFldExist === 0) {
    return {
      'background': '#ff0000 !important'
    }
  }
}
const testApi = () => {
  ElMessage({
    type: 'warning',
    message: '测试API--未完成'
  })
}
const dwsTopics = ref([])
const getDwsTopic = async() => {
  const res = await getAllDwsTopics()
  if (res.code === 0) {
    dwsTopics.value = res.data.dwsTopic
  }
}
const getTopicNameById = (id) => {
  if (id !== null) {
    for (let i = 0; i < dwsTopics.value.length; i++) {
      if (id === dwsTopics.value[i].ID) {
        return (dwsTopics.value[i].name)
      }
    }
  } else {
    return '未定义'
  }
}
const getTopicCodeById = (id) => {
  if (id !== null) {
    for (let i = 0; i < dwsTopics.value.length; i++) {
      if (id === dwsTopics.value[i].ID) {
        return (dwsTopics.value[i].code)
      }
    }
  } else {
    return '未定义'
  }
}
const joinTypeList = ref([])
const getJoinTypeList = async() => {
  joinTypeList.value = await getDict('joinType')
}
const apiType = ref([])
const getApiType = async() => {
  apiType.value = await getDict('apiType')
}
const requestType = ref([])
const getRequestType = async() => {
  requestType.value = await getDict('requestType')
}
const allOdsTbs = ref()
const getOdsTb = async() => {
  const res = await getAllOdsDbTables()
  if (res.code === 0) {
    allOdsTbs.value = res.data.odsDbTable
  } else {
    ElMessage({
      type: 'info',
      message: '获取ODS表名称失败'
    })
  }
}
const apiNameList = ref([])
const apiCodeList = ref([])
const setApiList = async() => {
  const res = await getAllDwsApis()
  if (res.code === 0) {
    const allDwsApi = res.data.dwsApi
    for (const one of allDwsApi) {
      apiNameList.value.push(one.name)
      apiCodeList.value.push(one.code)
    }
  } else {
    ElMessage({
      type: 'info',
      message: '获取接口数据配置失败'
    })
  }
}

const stateBoolean = (bool) => {
  if (bool !== null) {
    return bool ? '启用' : '停用'
  } else {
    return ''
  }
}
const init = async() => {
  await getDwsTopic()
  await getApiType()
  await getRequestType()
  await getJoinTypeList()
  await getOdsTb()
  await getTableData()
  await setApiList()
}

onMounted(async() => {
  await init()
})

</script>

<style>
.el-form-item{
  margin: 8px 0px 5px;
}
</style>
